/*
   Ejemplo de servidor SDP. Solo presenta en las trazas el mensaje recibido.
*/

#include <iostream>

#include <nemesis.h>
#include <nemesis.comm.h>
#include <nemesis.sdp.h>

class MyCommunicator : public sdp::Communicator {
public: 
   class MyInterface : public sdp::Interface {
   public:
      MyInterface (sdp::Communicator& sdpCommunicator, const int interface) : 
         sdp::Interface (sdpCommunicator, interface, "server SDP-SDP")
      {;}
      
      void receive (comm::Server&, const sdp::Message&) throw (RuntimeException);

      sdp_complete_interface (MyInterface);
   };
       
   MyCommunicator (sdp::Application& application, const int interface) :
      sdp::Communicator (application),
      a_interface (*this, interface)
   {
   }
   
private:
   MyInterface a_interface;

};

class EchoSDP : public sdp::Application {
public:
   EchoSDP ();
   
private:
   MyCommunicator* a_communicator;

   void initialize () throw (RuntimeException);
   void run () throw (RuntimeException);    
};

using namespace std;

int main (int argc, const char** argv)
{
   EchoSDP app;
   
   try {
      app.initCommandLine (argv, argc);
      app.start ();
   }
   catch (Exception& ex) {
      cout << ex.asString () << endl;
   }
   
   return 0;
}

EchoSDP::EchoSDP () :
   sdp::Application ("sdp_echo", "Servidor de operaciones aritmeticas con protocolo SDP-SDP", "1.0"),
   a_communicator (NULL)
{
   CommandLine& cl (CommandLine::instanciate ());

   cl.add ("interface", CommandLine::Argument::Mandatory, "Numero de interfaz SDP en el que escuchara mensajes");
}

void EchoSDP::initialize ()
   throw (RuntimeException)
{
   CommandLine& cl (CommandLine::instanciate ());

   a_communicator = new MyCommunicator (*this, cl.getIntegerValue ("interface"));

   sdp::Application::initialize ();
}

void EchoSDP::run () 
   throw (RuntimeException)
{
   LOGMETHOD (TraceMethod tm ("sdp_echo", "run", FILE_LOCATION));

   sdp::Application::run ();
   
   a_communicator->accept ();
}

void MyCommunicator::MyInterface::receive (Server& server, const sdp::Message& message)
   throw (RuntimeException)
{
   LOGMETHOD (TraceMethod tm ("MyCommunicator::MyInterface", "receive", FILE_LOCATION));
   
   string msg ("MyCommunicator::MyInterface::receive | ");
   msg += server.asString ();
   msg += " | Body: ";
   msg += nemesis::functions::asString (message.getBody ());
   Logger::information (msg, FILE_LOCATION);

   cout << msg << end << endl;
}

